//
//  CustomCell.m
//  AsynImageDownload
//
//  Created by Santiago Fontanarrosa on 6/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "CustomCell.h"

@interface CustomCell()

@property (nonatomic,retain) NSURLConnection *connection;
@property (nonatomic, retain) NSMutableData* data;

@end

@implementation CustomCell

@synthesize label = _label;
@synthesize image = _image;
@synthesize connection = _connection;
@synthesize data = _data;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

-(void)dealloc
{
    [self.connection cancel];
    self.connection = nil;
    self.data = nil;
    self.image = nil;
    self.label = nil;
    [super dealloc];
}

+(CustomCell*)newCustomCell
{
    CustomCell *cell = nil;
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell"
                                                 owner:self options:nil];
    for (id oneObject in nib) if ([oneObject isKindOfClass:[CustomCell class]])
        cell = (CustomCell *)oneObject;

    return cell;
}


- (void)loadImageFromURL:(NSString*)urlStr {
	if (self.connection!=nil) { [self.connection cancel];self.connection = nil;} //in case we are downloading a 2nd image
	if (self.data!=nil) { self.data = nil; }
	
}

#pragma mark - NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Image download failed with error %@",[error localizedDescription]);
}

- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData 
{
    if (self.data==nil) { _data = [[NSMutableData alloc] initWithCapacity:2048]; } 
    [self.data appendData:incrementalData];
}

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
	
	self.connection=nil;	
    self.image.image=[UIImage imageWithData:self.data];
    self.image.contentMode = UIViewContentModeScaleAspectFill;
    self.data=nil;
}


@end
